package com.mall.web.control.weishang;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.mall.biz.ImageUploadBizImpl;
import com.mall.biz.item.MallItemBizImpl;
import com.mall.biz.trade.TradeBizImpl;
import com.mall.biz.user.AddressBizImpl;
import com.mall.biz.user.record.CollectionBizImpl;
import com.mall.biz.weishang.DistributorBizImpl;
import com.mall.client.item.MallItemPriceService;
import com.mall.client.item.MallItemService;
import com.mall.client.mall.MallActivityService;
import com.mall.client.mall.MallService;
import com.mall.client.mallCategory.MallCategoryService;
import com.mall.client.order.MallItemOrderService;
import com.mall.client.region.AreaService;
import com.mall.client.region.CityService;
import com.mall.client.region.ProvinceService;
import com.mall.client.trade.TradeService;
import com.mall.client.user.AddressService;
import com.mall.client.user.CollectionService;
import com.mall.client.user.TransferAuditService;
import com.mall.client.user.UserExtendedService;
import com.mall.client.user.UserLevelService;
import com.mall.client.user.UserService;
import com.mall.common.util.PageUtil;
import com.mall.constant.UserConstant;
import com.mall.enums.AddressEnum;
import com.mall.enums.CollectionEnum;
import com.mall.enums.MallActivityEnum;
import com.mall.enums.UserEnum;
import com.mall.pojo.Address;
import com.mall.pojo.Area;
import com.mall.pojo.City;
import com.mall.pojo.Collection;
import com.mall.pojo.CollectionExample;
import com.mall.pojo.CollectionExample.Criteria;
import com.mall.pojo.Mall;
import com.mall.pojo.MallActivity;
import com.mall.pojo.MallCategory;
import com.mall.pojo.MallCategoryExample;
import com.mall.pojo.MallItem;
import com.mall.pojo.MallItemOrder;
import com.mall.pojo.MallItemPrice;
import com.mall.pojo.Province;
import com.mall.pojo.TradeExample;
import com.mall.pojo.TransferAudit;
import com.mall.pojo.User;
import com.mall.pojo.UserExtended;
import com.mall.pojo.UserLevel;
import com.mall.query.MallActivityQuery;
import com.mall.query.MallItemQuery;
import com.mall.query.Page;
import com.mall.query.TradeRecordQuery;
import com.mall.query.weishang.UserQuery;
import com.mall.vo.common.CategoryVO;
import com.mall.vo.eshop.CollectionVO;
import com.mall.vo.item.MallItemVO;
import com.mall.vo.user.UserVO;
import com.mall.web.annotation.AdminSecurity;
import com.mall.web.annotation.WeishangSecurity;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.SplitUtil;
import com.mall.web.util.WebUtil;
import com.mall.web.vo.ResponseEntity;

@Controller
@RequestMapping("/weishang/distributor/")
public class WeishangDistributorController {
	@Autowired
	private DistributorBizImpl distributorBiz;
	@Autowired
	private UserService userService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private UserExtendedService userExtendedService;
	@Autowired
	private AddressBizImpl addressBizImpl;
	@Autowired
	private UserLevelService userLevelService;
	@Autowired
	private MallItemService mallItemService;
	@Autowired
	private MallCategoryService mallCategoryService;
	@Autowired
	private MallItemPriceService mallItemPriceService;
	@Autowired
	private CollectionBizImpl collectionBizImpl;
	@Autowired
	private CollectionService collectionService;
	@Autowired
	private MallItemOrderService mallItemOrderService;
	@Autowired
	private TradeService tradeService;
	@Autowired
	private MallService mallService;
	@Autowired
	private ProvinceService provinceService;
	@Autowired
	private CityService cityService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private MallActivityService mallActivityService;
	@Autowired
	private TradeBizImpl tradeBizImpl;
	@Autowired
	private MallItemBizImpl mallItemBizImpl;
	@Autowired
	private TransferAuditService transferAuditService;
	@Autowired
	private ImageUploadBizImpl imageUploadBizImpl;
	
	// 图片保存的文件夹名字
	private final String folder = "weishang";
	
	/**
	 * 分销商列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("distributorList")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String distributorList(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		distributorListModelMap(request,response,modelMap);
		return "weishang/distributor/distributorList";
		
	}
	
	@RequestMapping("distributorListMore")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String distributorListMore(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		distributorListModelMap(request,response,modelMap);
		return "weishang/distributor/distributorListMore";
	}
	
	public ModelMap distributorListModelMap(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		//分页
		Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize",PageUtil.PAGE_SIZE_APP);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);
		
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		String keyWord = HttpUtil.getURLDecoderValueFromRequest(request, "keyWord");
		Integer level = HttpUtil.getIntegerValueFromRequest(request, "level");
		String orderBy =  HttpUtil.getStringValueFromRequest(request, "orderBy");//0 等级降序    1等级升序
		
		UserQuery userQuery = new UserQuery();
		userQuery.setType(UserEnum.FENXIAOSHANG.getCode());
		userQuery.setPage(page);
		userQuery.setKeyWord(keyWord);
		userQuery.setLevel(level);
		userQuery.setOnlyKey(onlyKey);
		userQuery.setOrderBy(orderBy);
		List<UserVO> userVOList = this.distributorBiz.getUserVOListByQuery(userQuery);
		List<UserLevel> userLevelList = this.userLevelService.getUserLevelListByKey(onlyKey);
		
		modelMap.put("userLevelList", userLevelList);
		modelMap.put("userVOList", userVOList);
		return modelMap;
	}
	
	/**
	 * 商品列表页
	 * @param request  
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("distributorItemList")
	@WeishangSecurity
	public String distributorItemList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		distributorItemListModelMap(request,response,modelMap);
		return "weishang/item/distributorItemList";
	}
	/**
	 * 多图的商品列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("picSItemList")
	@WeishangSecurity
	public String picSItemList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		
		Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize", PageUtil.PAGE_SIZE);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);
		
		//获取满足条件的所有商品
		MallItemQuery mallItemQuery = new MallItemQuery();
		mallItemQuery.setPage(page);
		mallItemQuery.setOnlyKey(onlyKey);
		mallItemQuery.setOrderBy("id desc");
		mallItemQuery.setStatus(0);
		List<MallItem> mallItemList = this.mallItemBizImpl.getMallItemByQuery(mallItemQuery);
		List<MallItemVO> mallItemVOList = new ArrayList<MallItemVO>();
		if(mallItemList != null && mallItemList.size() > 0){
			for(MallItem mallItem : mallItemList){			
				MallItemPrice mallItemPrice = this.mallItemPriceService.getMallItemPriceByLevelAndKey(user.getLevel().longValue(), onlyKey, mallItem.getId(),0);
				if(mallItemPrice == null){
					mallItemPrice = this.mallItemPriceService.getMallItemPriceByLevelAndKey(1l, onlyKey, mallItem.getId(), 0);
				}
				MallItemVO mallItemVO = new MallItemVO();
				mallItemVO.setMallItem(mallItem);
				mallItemVO.setMallItemPrice(mallItemPrice);
				mallItemVOList.add(mallItemVO);
			}
		}
		modelMap.put("mallItemVOList", mallItemVOList);
		return "weishang/item/picSItemList";
	}
	
	/**
	 * 商品列表加载更多
	 * @param request  
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("distributorItemListMore")
	@WeishangSecurity
	public String distributorItemListMore(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		distributorItemListModelMap(request,response,modelMap);
		return "weishang/item/distributorItemListMore";
	}
	
	
	/**
	 * 分销商获得商品列表的map
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	public ModelMap distributorItemListModelMap(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		
		Long categoryId = HttpUtil.getLongValueFromRequest(request, "categoryId");
		Integer stock = HttpUtil.getIntegerValueFromRequest(request, "stock");//库存    0：已售罄
		String orderBy = HttpUtil.getStringValueFromRequest(request, "orderBy");//排序
		
		//获取供应商的类目列表
		MallCategoryExample mallCategoryExample = new MallCategoryExample();
		com.mall.pojo.MallCategoryExample.Criteria categoryCriteria = mallCategoryExample.createCriteria();
		categoryCriteria.andCommOnlyKeyEqualTo(onlyKey);
		categoryCriteria.andParentIdEqualTo(0);
		categoryCriteria.andStatusEqualTo(0);
		List<MallCategory> firstCategoryList = this.mallCategoryService.getMallCategoryList(mallCategoryExample);
		
		List<CategoryVO> categoryVOList = new ArrayList<CategoryVO>();
		if(firstCategoryList != null && firstCategoryList.size() > 0){
			for(MallCategory firstCategory : firstCategoryList){
				CategoryVO categoryVO = new CategoryVO();
				List<MallCategory> secCategoryList = this.mallCategoryService.getSecMallCategoryListByParentMallCategoryId(firstCategory.getId());
				categoryVO.setFirstCategory(firstCategory);
				categoryVO.setSecCategoryList(secCategoryList);
				categoryVOList.add(categoryVO);
			}
		}
		
		// 设置分页
		Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize", PageUtil.PAGE_SIZE);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);
		
		//获取满足条件的所有商品
		MallItemQuery mallItemQuery = new MallItemQuery();
		mallItemQuery.setPage(page);
		mallItemQuery.setItemCategoryId(categoryId);
		mallItemQuery.setOnlyKey(onlyKey);
		mallItemQuery.setStock(stock);
		mallItemQuery.setOrderBy(orderBy);
		mallItemQuery.setStatus(0);
		List<MallItem> mallItemList = this.mallItemBizImpl.getMallItemByQuery(mallItemQuery);
		
		List<MallItemVO> mallItemVOList = new ArrayList<MallItemVO>();
		if(mallItemList != null && mallItemList.size() > 0){
			for(MallItem mallItem : mallItemList){			
				MallItemPrice mallItemPrice = this.mallItemPriceService.getMallItemPriceByLevelAndKey(user.getLevel().longValue(), onlyKey, mallItem.getId(),0);
				if(mallItemPrice == null){
					mallItemPrice = this.mallItemPriceService.getMallItemPriceByLevelAndKey(1l, onlyKey, mallItem.getId(), 0);
				}
				MallItemVO mallItemVO = new MallItemVO();
				mallItemVO.setMallItem(mallItem);
				mallItemVO.setMallItemPrice(mallItemPrice);
				mallItemVO.setPic(SplitUtil.convertStrToArray(mallItem.getMainPic(), 0));
				mallItemVO.setIsCollection(this.collectionBizImpl.isCollection(onlyKey, mallItem.getId(), user, CollectionEnum.WEISHANG.getCode()));
				mallItemVOList.add(mallItemVO);
			}
		}
		
		modelMap.put("categoryVOList", categoryVOList);
		modelMap.put("mallItemVOList", mallItemVOList);
		modelMap.put("user", user);
		return modelMap;
	}
	
	/**
	 * 用户购物车列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("shoppingCartList")
	@WeishangSecurity
	public String shoppingCartList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		
		CollectionExample example = new CollectionExample();
		com.mall.pojo.CollectionExample.Criteria criteria = example.createCriteria();
		criteria.andCommOnlyKeyEqualTo(onlyKey);
		criteria.andUserIdEqualTo(user.getId());
		criteria.andStatusEqualTo(0);
		List<Collection> itemCollectionList = this.collectionService.getCollectionByExample(example);
		List<CollectionVO> collectionVOList = this.collectionBizImpl.getCollectionVOListByCollectionList(itemCollectionList);
		
		modelMap.put("collectionVOList", collectionVOList);
		return "weishang/item/shoppingCartList";
	}
	
	/**
	 * 加入购物车
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("itemCollection")
	@ResponseBody
	public ResponseEntity<String> itemCollection(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<>();
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		Long mallItemId = HttpUtil.getLongValueFromRequest(request, "mallItemId");
		if(mallItemId == null || mallItemId <= 0){
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("id不存在");
			return responseEntity;
		}
		Collection collection = null;
		
		List<Collection> collectionList =  getCollectionListByStatusAndMallItemId(mallItemId,CollectionEnum.COLLECTION.getCode(),user.getId());
		if (collectionList != null && collectionList.size()>0 ) {
			collection = collectionList.get(0);
			if(collection != null){
				responseEntity.initErrorResponseEntity(null, "collection is not null");
				return responseEntity;
			}else{
				collection = new Collection();
				collection.setCommOnlyKey(onlyKey);
				collection.setMallId(mallItemId);
				collection.setStatus(0);
				collection.setType(CollectionEnum.WEISHANG.getCode());
				collection.setUserId(user.getId());
				this.collectionService.insertCollection(collection);
				
				responseEntity.initSuccResponseEntity(null, "collection success");
				return responseEntity;
			}
		}
		
		collectionList = getCollectionListByStatusAndMallItemId(mallItemId,CollectionEnum.UNCOLLECTION.getCode(),user.getId());//已经收藏过，但当前状态是取消加入购物车
		if (collectionList != null && collectionList.size()>0 ) {
			collection = collectionList.get(0);
				
			if(collection != null){
				collection.setStatus(0);
				this.collectionService.modifyCollection(collection);
				responseEntity.initSuccResponseEntity(null, "collection success");
				return responseEntity;
			}
		}else{
			collection = new Collection();
			collection.setCommOnlyKey(onlyKey);
			collection.setMallId(mallItemId);
			collection.setStatus(0);
			collection.setType(CollectionEnum.WEISHANG.getCode());
			collection.setUserId(user.getId());
			this.collectionService.insertCollection(collection);
			responseEntity.initSuccResponseEntity(null, "collection success");
			return responseEntity;
		}
		return responseEntity;
	}
	
	
	private List<Collection> getCollectionListByStatusAndMallItemId(Long mallItemId,Integer status,Long userId){
		
		CollectionExample example = new CollectionExample();
		Criteria criteria = example.createCriteria();
		criteria.andMallIdEqualTo(mallItemId);
		criteria.andUserIdEqualTo(userId);
		criteria.andStatusEqualTo(status);
		List<Collection> collectionList = this.collectionService.getCollectionByExample(example);
		return collectionList;
		
		
	}
	
	/**
	 * 取消加入购物车
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("itemCollectionCancel")
	@ResponseBody
	public ResponseEntity<String> itemCollectionCancel(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<>();
		Long collectionId = HttpUtil.getLongValueFromRequest(request, "collectionId");
		if(collectionId == null || collectionId <= 0){
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("id不存在");
			return responseEntity;
		}
		
		//从购物车删除
		Collection collection = this.collectionService.getCollectionById(collectionId);
		collection.setStatus(4);
		this.collectionService.modifyCollection(collection);
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("修改成功");
		return responseEntity;
	}
	
	/**
	 * 购物车首页
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("shoppingCart")
	@WeishangSecurity
	public String shoppingCart(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		List<Collection> itemCollectionList = this.collectionBizImpl.getCollectionByUserIdAndOnlyKey(user.getId(), onlyKey, null, 
												null, CollectionEnum.WEISHANG.getCode(), 0);
		List<CollectionVO> collectionVOList = this.collectionBizImpl.getCollectionVOListByCollectionList(itemCollectionList);
		
		List<Address> addressList = this.addressBizImpl.getAddressListByUserAndstatus(user.getId(), onlyKey, null, AddressEnum.DEFAULTADDRESS.getCode());
		Address address = this.addressBizImpl.getFirstAddress(addressList);
		
		modelMap.put("user", user);
		modelMap.put("address", address);
		modelMap.put("collectionVOList", collectionVOList);
		return "weishang/distributor/shoppingCart";
	}
	
	/**
	 * 购物车下单页面
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value="shoppingCartOrderAction",method=RequestMethod.POST)
	@WeishangSecurity
	public String shoppingCartOrder(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		String mallItemIds[] = HttpUtil.getStringValueFromRequest(request, "itemIds").split(",");//商品id
		String singlePrices[] = HttpUtil.getStringValueFromRequest(request, "singlePrices").split(",");//商品单价
		String nums[] = HttpUtil.getStringValueFromRequest(request, "itemNumbers").split(",");//商品数量
		
		long price = 0l;//下单商品总价
		
		Long orPrice =0l;//下单商品总原价
		MallItemOrder mallItemOrder = new MallItemOrder();
		
		List<MallItemVO> mallItemVOList = new ArrayList<>();
		MallItemVO mallItemVO = null;
		if(mallItemIds != null && singlePrices != null && nums != null && mallItemIds.length > 0 && singlePrices.length > 0 && nums.length > 0){
			Integer itemCounts = 0;
			for(int i = 0;i < mallItemIds.length;i++){
				mallItemVO = new MallItemVO();
				Long mallItemId = Long.parseLong(mallItemIds[i]);
				Integer itemNo = Integer.parseInt(nums[i]);
				MallItem mallItem = mallItemService.getMallItemById(mallItemId);
				//mallItemVO.setMallItem(mallItem);
				mallItemVO.setNo(itemNo);
				mallItemVO.setMallItemTitle(mallItem.getTitleName());
				BigDecimal show = new BigDecimal(singlePrices[i]);
				mallItemVO.setPrice(show.doubleValue() + "");
				mallItemVO.setPic(SplitUtil.convertStrToArray(mallItem.getMainPic(), 0));
				mallItemVO.setMallItemId(mallItemId);
				mallItemVOList.add(mallItemVO);
				mallItemVO.setDescription(mallItem.getDescription());
				itemCounts += itemNo;
				price = price + show.multiply(new BigDecimal(100)).longValue() * itemNo;
				orPrice = orPrice + mallItem.getPrice()*itemNo;
			}
			String json = JSONArray.toJSONString(mallItemVOList);
			mallItemOrder.setBuyItemsJson(json);
			mallItemOrder.setBuyCount(itemCounts);
			mallItemOrder.setPrice(price);
			mallItemOrder.setDiscountPrice(orPrice-price);
		}
		
		mallItemOrder.setCommOnlyKey(onlyKey);
		mallItemOrder.setBuyUserId(user.getId());
		mallItemOrder.setSellerId(this.mallService.getMallByOnlyKey(onlyKey).getSellerId());
		mallItemOrder.setMealNum(1);
		mallItemOrder.setMallId(this.mallService.getMallByOnlyKey(onlyKey).getId());
		mallItemOrder.setStatus(0);
		mallItemOrder.setType(9);
		mallItemOrder.setGmtCreate(new Date());
		mallItemOrder.setAttribute(tradeService.generateOrderNo());
		mallItemOrder.setGmtModify(new Date());
		this.mallItemOrderService.insertMallItemOrder(mallItemOrder);
		
		Long orderId = mallItemOrder.getId();
		if (orderId == null || orderId == 0) {
			return "weishang/trade/orderError";
		}
		return "redirect:/weishang/trade/order.htm?mallItemOrderId="+orderId;
	}
	
	
	
	
	/**
	 * 分销商详情（供应商看到的)
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("distributorDetail")
	@WeishangSecurity
	public String distributorDetail(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		Long userId = HttpUtil.getLongValueFromRequest(request, "userId");
		if(userId == null || userId <= 0){
			return null;
		}
		User user = this.userService.getUserByUserId(userId);
		User currentUser = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Mall mall = this.mallService.getMallByOnlyKey(onlyKey);
		Address address = new Address();
		List<Address> addressList = this.addressBizImpl.getAddressListByUserAndstatus(userId, onlyKey, null, AddressEnum.DEFAULTADDRESS.getCode());
		if(addressList != null && addressList.size() >0){
			address = addressList.get(0);
		}
		UserVO userVO = new UserVO();
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(userId);
		UserLevel userLevel = this.userLevelService.getUserLevelByLevelAndKey(user.getLevel().intValue() , onlyKey);
		//JSONObject obj = JSONObject.fromObject(attributeJson);//将json字符串转换为json对象
		//UserVO userVO = (UserVO)JSONObject.toBean(obj,UserVO.class);
		userVO.setUser(user);
		userVO.setAddress(address);
		userVO.setUserExtended(userExtended);
		userVO.setUserLevel(userLevel);
		modelMap.put("userVO", userVO);
		
		if(currentUser.getType() == UserConstant.TYPE_MANAGE){
			List<UserLevel> userLevelList = this.userLevelService.getUserLevelListByKey(onlyKey);
			modelMap.put("userLevelList", userLevelList);
		}
		TradeRecordQuery tradeRecordQuery = new TradeRecordQuery();
		tradeRecordQuery.setType(12);
		tradeRecordQuery.setOnlyKey(onlyKey);
		tradeRecordQuery.setStatus(4);
		tradeRecordQuery.setUserId(user.getId());
		TradeExample example = this.tradeBizImpl.getTradeExampleByQuery(tradeRecordQuery);
		Long sumPrice = this.tradeService.getSumPriceByExample(example);
		modelMap.put("currentUser", currentUser);
		modelMap.put("sumPrice", sumPrice);
		modelMap.put("mall", mall);
		return "weishang/distributor/distributorDetail";
		
	}
	
	
	/**
	 * 分销商修改个人信息
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("distributorModifyInfoAction")
	@Transactional
	public String distributorModifyInfoAction(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Date gmtModify = new Date();
		
		String userName = HttpUtil.getStringValueFromRequest(request, "userName");
		if(!user.getUserName().equals(userName)){
			user.setUserName(userName);
			user.setGmtModify(gmtModify);
			this.userService.modifytUserByPrimaryKey(user);
		}
		
		List<Address> addressList = this.addressBizImpl.getAddressListByUserAndstatus(user.getId(), onlyKey, null, AddressEnum.DEFAULTADDRESS.getCode());
		if(addressList == null || addressList.size() <= 0){
			return null;
		}
		
		Address address = addressList.get(0);
		Integer areaId = HttpUtil.getIntegerValueFromRequest(request, "areaId");
		Integer cityId = HttpUtil.getIntegerValueFromRequest(request, "cityId");
		Integer provinceId = HttpUtil.getIntegerValueFromRequest(request, "provinceId");
		String detailAddress = HttpUtil.getStringValueFromRequest(request, "detailAddress");
		
		//有一个地址的变化就更新地址
		if(address.getAreaId() != areaId || address.getCityId() != cityId || address.getProvinceId() != provinceId || !detailAddress.equals(detailAddress)){
			address.setAreaId(areaId);
			address.setCityId(cityId);
			address.setProvinceId(provinceId);
			
			Province province = this.provinceService.getProvinceById(provinceId);
			City city = this.cityService.getCityById(cityId);
			Area area = this.areaService.getAreaByAreaId(areaId);
			address.setAddress(province.getProvinceName()+city.getCityName()+area.getAreaName()+detailAddress);
			address.setAttribute(province.getProvinceName()+" "+city.getCityName()+" "+area.getAreaName());
			address.setGmtModify(gmtModify);
			address.setName(userName);
			this.addressService.modifyAddressByPrimaryKey(address);
		}
		
		String accountName = request.getParameter("accountName");
		String accountBank = request.getParameter("accountBank");
		String accountCard = request.getParameter("accountCard");
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(user.getId());
		if(userExtended != null){//equals左边不能为null，不然会空指针
			if(!accountName.equals(userExtended.getAccountName()) || !accountBank.equals(userExtended.getAccountBank()) || 
					!accountCard.equals(userExtended.getAccountCard())){
				userExtended.setAccountName(accountName);
				userExtended.setAccountBank(accountBank);
				userExtended.setAccountCard(accountCard);
				userExtended.setGmtModify(gmtModify);
				this.userExtendedService.updateExtendedByPrimaryKey(userExtended);
			}
		}
		return "redirect:/weishang/distributor/distributorDetail?userId="+user.getId();
	}
	
	
	/**
	 * 供应商主动修改分销商级别
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("modifyUserLevel")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@ResponseBody
	public ResponseEntity<String> modifyUserLevel(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		Integer level = HttpUtil.getIntegerValueFromRequest(request, "level");
		Long userId = HttpUtil.getLongValueFromRequest(request, "userId");
		User user = this.userService.getUserByUserId(userId);
		if(user == null || level == null){
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("无法修改");
			return responseEntity;
		}
		user.setLevel(level.shortValue());
		user.setGmtModify(new Date());
		this.userService.modifytUserByPrimaryKey(user);
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("修改成功");
		return responseEntity;
	}
	
	
	
	/**
	 * 分销商消息列表
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("messageList")
	public String messageList(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		messageModelMap(request,response,modelMap);
		return "weishang/supplier/messageList";
	}
	
	
	public ModelMap messageModelMap(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		//分页
		Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize",PageUtil.PAGE_SIZE_MALL);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);
		
		MallActivityQuery mallActivityQuery = new MallActivityQuery();
		mallActivityQuery.setCommkey(onlyKey);
		mallActivityQuery.setSuitPerson(user.getLevel().intValue());
		mallActivityQuery.setOrderBy("id desc");
		mallActivityQuery.setStatus(MallActivityEnum.USINGACTIVITY.getCode());
		mallActivityQuery.setType(MallActivityEnum.SELLERACTIVITY.getCode());
		List<MallActivity> mallActivityList = this.mallActivityService.getMallActivityListByLevel(user.getLevel().intValue(), onlyKey);
		//List<MallActivity> mallActivityList = this.mallActivityService.getMallActivityList(mallActivityQuery, page);
		
		modelMap.put("mallActivityList", mallActivityList);
		return modelMap;
	}
	
	
/*	
	@RequestMapping("doRechargeAction")
	public ResponseEntity<String> doRechargeAction(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		
				
		Integer rechargeType = HttpUtil.getIntegerValueFromRequest(request, "rechargeType");
		String money = HttpUtil.getStringValueFromRequest(request, "money");
		Long rechargeMoney = MoneyUtil.getPriceByString(money);
		
		ResponseEntity<String> responseEntity = new ResponseEntity<String>();
		
		doRechargeAction(rechargeType,rechargeMoney,request);
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("充值成功");
		return responseEntity;
		
	}*/
	
	
	/**
	 * 分销商还没有充值预付款时，跳转至此页面充值
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("rechargeCenter")
	public String rechargeBalance(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(user.getId());
		
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		List<UserLevel> userLevelList = this.userLevelService.getUserLevelListByKey(onlyKey);
		//判断是否有审核中的转账信息
		List<TransferAudit> transferAuditList = this.transferAuditService.getTransferAuditListByUserAndKey(user.getId(), onlyKey, 0,user.getPhone());
		modelMap.put("user", user);
		modelMap.put("userExtended", userExtended);
		modelMap.put("userLevelList", userLevelList);
		modelMap.put("transferAuditList", transferAuditList);
		return "weishang/distributor/rechargeCenter";
	}
	
	/**
	 * 点击充值预付款按钮时跳转上传转账凭证页面
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("uploadTransferAudit")
	public String uploadTransferAudit(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Integer level = HttpUtil.getIntegerValueFromRequest(request, "level");
		Integer type = HttpUtil.getIntegerValueFromRequest(request, "type");
		Mall mall = this.mallService.getMallByOnlyKey(onlyKey);
		if(level == null || mall == null){
			return null;
		}
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(mall.getSellerId());
		modelMap.put("level", level);
		modelMap.put("type", type);
		modelMap.put("userExtended", userExtended);
		return "weishang/distributor/uploadTransferAudit";
	}
	
	
	/**
	 * 点击充值预付款按钮时跳转上传转账凭证页面
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("doRecharge")
	public String doRecharge(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Integer level = HttpUtil.getIntegerValueFromRequest(request, "level");
		Integer type = HttpUtil.getIntegerValueFromRequest(request, "type");
		Mall mall = this.mallService.getMallByOnlyKey(onlyKey);
		if(level == null || mall == null){
			return null;
		}
		UserExtended userExtended = this.userExtendedService.getUserExtendByUserId(mall.getSellerId());
		modelMap.put("level", level);
		modelMap.put("type", type);
		modelMap.put("userExtended", userExtended);
		return "weishang/distributor/doRecharge";
	}
	
	/**
	 * 1万元以下直接执行微信支付
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("rechargeBalanceAction")
	public String rechargeBalanceAction(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
		return "weishang/distributor/rechargeBalanceAction";
	}
	
	
	
	
	
	/**
	 *上传转账成功后跳转至成为会员首页
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@WeishangSecurity
	@RequestMapping("uploadTransferAuditAction")
	public String uploadTransferAuditAction(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap,
			@RequestParam("transferVoucher") MultipartFile[] transferVoucher){
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Integer level = HttpUtil.getIntegerValueFromRequest(request, "level");
		Integer type = HttpUtil.getIntegerValueFromRequest(request, "type");//0会员充值   1 充值货款
		Mall mall = this.mallService.getMallByOnlyKey(onlyKey);
		String transferRemark = HttpUtil.getStringValueFromRequest(request, "transferRemark");
		TransferAudit transferAudit = new TransferAudit();
		transferAudit.setCommOnlyKey(onlyKey);
		transferAudit.setMallId(mall.getId());
		transferAudit.setUserId(user.getId());
		transferAudit.setPhone(user.getPhone());
		transferAudit.setStatus(0);
		transferAudit.setTransferRemark(transferRemark);
		transferAudit.setTransferVoucher(this.imageUploadBizImpl.getWeishangUploadPicFullName(transferVoucher, request, folder));
		transferAudit.setType(type);
		this.transferAuditService.insertTransferAudit(transferAudit);
		if(type == 0){
			//会员充值时，设置用户级别为想要成为级别的负数
			user.setLevel(Short.parseShort("-"+level));
			user.setGmtModify(new Date());
			this.userService.modifytUserByPrimaryKey(user);
			return "redirect:/weishang/distributor/rechargeCenter.htm";
		}
		if(type == 1){
			return "redirect:/weishang/distributor/distributorDetail.htm?userId="+user.getId();
		}
		return null;
	}
	
	
	
}
